package cn.edu.bupt.freewings.forum.persistence;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import cn.edu.bupt.freewings.forum.persistence.EntityManagerHelper;
import cn.edu.bupt.freewings.forum.persistence.Post;

/**
 * @author hubaiyu (hubaiyu@gmail.com)
 *
 */

@SuppressWarnings("unchecked")
public class TopicDAO {
	public void save(Topic entity){
		try{
			EntityManagerHelper.getEntityManager().persist(entity);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void delete(Topic entity){
		try{
			Topic ref = EntityManagerHelper.getEntityManager().getReference(Topic.class, entity.getId());
			EntityManagerHelper.getEntityManager().remove(ref);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public Topic update(Topic entity){
		try{
			return EntityManagerHelper.getEntityManager().merge(entity);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public List<Topic> getByProjectId(Integer projectId){
		try{
			String queryString = "select model from Topic model where model.projectId = :projectId";
			Query query = EntityManagerHelper.getEntityManager().createQuery(queryString);
			query.setParameter("projectId", projectId);
			return query.getResultList();
		}catch(Exception e){
			e.printStackTrace();
			return new ArrayList<Topic>(0);
		}
	}
}
